package model;

import helperclasses.DbUtil;
import helperclasses.MyDataColector;
import helperclasses.Product;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import org.apache.catalina.connector.Request;

public class ViewProduct {
	private Product product = new Product();

	public ViewProduct() {

	}

	private Connection getConnection() throws SQLException {

		DataSource ds = DbUtil.getInstance().getDataSource();
		Connection conn = ds.getConnection();
		return conn;
	}

	public Product getProduct() {
		return product;
	}

	public void setProduct(Product product) {
		this.product = product;
	}

	public void getDetails(int productId) throws SQLException {
		Connection conn = getConnection();
		Statement st = conn.createStatement();
		String sql;
		ResultSet result;
		try {
			sql = "SELECT prod.produs_id, prod.nume, prod.valoare, prod.pret_iesire, prod.tip_nir, ps.cantitate, ps.valoare_in_stoc, um.tip "
					+ " FROM produse prod "
					+ " NATURAL JOIN produse_in_stoc ps "
					+ " NATURAL JOIN unitate_masura um "
					+ " WHERE produs_id=" + productId;
			result = st.executeQuery(sql);
			while (result.next()) {
				product.setProductId(productId);
				product.setProductName(result.getString("nume"));
				product.setValoare(Double.parseDouble(result.getString("valoare")));
				product.setPretIesire(Double.parseDouble(result.getString("pret_iesire")));
				// product.setPretIntrare(Double.parseDouble(result.getString("pret_intrare")));
				product.setTipNir(Integer.parseInt(result.getString("tip_nir")));
				product.setCantitate(Integer.parseInt(result.getString("cantitate")));
				product.setValoareInStoc(Double.parseDouble(result.getString("valoare_in_stoc")));
				product.setUnitateMasura(result.getString("tip"));
			}
			if (product.getTipNir() == 3) {
				sql = "SELECT prod.nume, ret.produs_id_retetar, ret.valoare FROM produse prod JOIN retetar ret"
						+ " WHERE prod.produs_id=ret.produs_id_retetar AND cocktail_id=" + productId;
				result = st.executeQuery(sql);
				while (result.next()) {
					Product ingredient = new Product();
					ingredient.setProductId(Integer.parseInt(result.getString("produs_id_retetar")));
					ingredient.setProductName(result.getString("nume"));
					ingredient.setValoareInStoc(Double.parseDouble(result.getString("valoare")));
					product.getIngredients().put(ingredient.getProductId(), ingredient);
				}
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {

			st.close();
			conn.close();
		}
	}

}
